package william.tree;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @author ZhangShenao
 * @date 2024/3/21
 * @description <a href="https://leetcode.cn/problems/binary-tree-paths/description/">...</a>
 */
public class Leetcode257_二叉树的所有路径 {
    private class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    /**
     * 采用全局变量,保存所有路径
     */
    private List<String> paths = new ArrayList<>();

    /**
     * 采用递归算法
     * 递归遍历二叉树,在路径上追加当前节点的值,直到遇到叶子节点,在追加值后,将当前的完整路径保存起来
     */
    public List<String> binaryTreePaths(TreeNode root) {
        //递归调用
        dfs(root, "");

        //返回结果
        return paths;
    }

    /**
     * 递归调用
     * 深度优先遍历二叉树,并将当前节点的值追加到前缀路径中
     */
    private void dfs(TreeNode node, String prePath) {
        //递归终止条件
        if (node == null) {
            return;
        }

        //将当前节点值追加到前缀路径中
        prePath += node.val;

        //遇到叶子节点,说明当前已经是一条完整路径,保存在结果中
        if (node.left == null && node.right == null) {
            paths.add(prePath);
            return;
        }

        //遇到非叶子节点,继续递归处理左、右子树
        prePath += "->";
        dfs(node.left, prePath);
        dfs(node.right, prePath);

    }
}
